package cn.com.tom.servlet;

import cn.com.tom.bean.Company;
import cn.com.tom.service.CompanyService;
import cn.com.tom.service.impl.CompanyServiceImpl;
import cn.com.tom.util.Uploads;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/company/*")
public class CompanyServlet extends BaseServlet {
    CompanyService servie = new CompanyServiceImpl();

    public void admin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Company> list = servie.list();
        request.setAttribute("companys", list);
        forward(request, response, "admin/company.jsp");
    }

    public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String imagePath = "";
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        upload.setHeaderEncoding("UTF-8");
        Map<String, Object> map = new HashMap<>();
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem item : fileItems) {
            if (item.isFormField()) {//1:非文件
                map.put(item.getFieldName(), item.getString("UTF-8"));
            } else {//2:文件
                if ("imageFile".equals(item.getFieldName())) {
                    imagePath = Uploads.uploadImage(item, request);
                }
            }
        }
        Company bean = new Company();
        BeanUtils.populate(bean, map);
        if (imagePath != null && !"".equals(imagePath)) {
            bean.setLogo(imagePath);
        }

        if (servie.save(bean)) {
            redirect(request,response,"/company/admin");
        } else {
            forwardError(request, response, "保存失败");
        }
    }

    public void remove(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] idS = request.getParameterValues("id");

        List<Integer> list = new ArrayList();
        for (int i = 0; i < idS.length; i++) {
            list.add(Integer.valueOf(idS[i]));
        }
        if (servie.remove(list)) {
            redirect(request,response,"/company/admin");
        } else {
            forwardError(request, response, "删除失败");
        }
    }
}
